package rabc.service;

import rabc.domain.dto.RoleDto;
import rabc.domain.entity.Role;
import rabc.domain.vo.RoleVo;
import rabc.domain.vo.Result;

import java.util.Arrays;
/**
 * 业务层-角色
 *
 * @author 朱磊
 * @since 2025/4/20 21:41
 */
public class   Roleservice {
    public static int DATA_SIZE = 100;
    public static Role[] data = new Role[DATA_SIZE+1];
    public static int idCounter = 1;

    public static RoleVo convertToVo(Role role){
        return new RoleVo(role.id,role.name,role.dataScope);
    }

    public static Role createEntity(RoleDto dto, int id){
        Role  role = new Role(dto.name,dto.dataScope);
        role.id = id;
        return role;
    }
    public static void updataEntity(RoleDto dto,Role role){
        role.name = dto.name;
        role.dataScope = dto.dataScope;
    }
    public static Result list(){
        RoleVo[] temp = new RoleVo[DATA_SIZE];
        int length=0;
        for (int i = 1; i < idCounter; i++) {

            if (data[i] != null) {
                temp[i] = convertToVo(data[i]);
            }
        }
        return Result.success("查询成功", Arrays.copyOf(temp,length));
    }
    public static Result create(RoleDto dto){
        if (idCounter > DATA_SIZE){
            return Result.failure("角色数据已满");
        }
        Role role = createEntity(dto,idCounter++);
        data[role.id] = role;
        return Result.success("创建成功",null);
    }
    public static boolean existsById(int id){
        return id>=1&&id<idCounter&&data[id]!=null;
    }
    public static Role findById(int id){
        if (!existsById(id)){
            return null;
        }
        return data[id];
    }
    public static Result update(RoleDto dto,int id){
        if (!existsById(id)){
            return Result.failure("角色不存在");
        }

        updataEntity(dto,data[id]);
        return Result.success("更新成功",null);
    }
    public static Result delete(int id){
        if (!existsById(id)){
            return Result.failure("角色不存在");
        }
        if (UserService.roleInUse(id)){
            return Result.failure("删除失败，还有用户在使用该角色，不能删除");
        }
        data[id]=null;
        return Result.success("删除成功",null);
    }
}
